#include "speedreaderlabel.h"
#include <QPainter>

SpeedReaderLabel::SpeedReaderLabel(QWidget *parent) :
    QLabel(parent)
{
    this->verticalPointerOffset = 0;
    this->setMinimumHeight(QFontMetrics(this->font()).height() + this->height() / 8 * 10);
    this->setMaximumHeight(this->minimumHeight());
    this->setAutoFillBackground(true);
    this->symbolColor = "";

    QPalette pal = this->palette();
    pal.setColor(QPalette::Window, QColor(Qt::white));
    this->setPalette(pal);
}

void SpeedReaderLabel::processWordOffset(const int &verticalPointerOffset)
{
    this->verticalPointerOffset = (verticalPointerOffset + 0.6) * QFontMetrics(this->font()).width("1");
    this->coloredSymbolPosition = verticalPointerOffset;
}

void SpeedReaderLabel::setSymbolColor(const QString &symbolColor)
{
    this->symbolColor = symbolColor;
}

void SpeedReaderLabel::setFont(const QFont &font)
{
    QLabel::setFont(font);
    this->setMinimumHeight(QFontMetrics(this->font()).height() + this->height() / 8 * 10);
    this->setMaximumHeight(this->minimumHeight());
}

void SpeedReaderLabel::paintEvent(QPaintEvent *e)
{
    QLabel::paintEvent(e);

    QPainter p(this);
    QPen pen(Qt::black);
    pen.setWidth(2);

    p.setPen(pen);
    p.drawLine(0, 1, this->width(), 1);
    p.drawLine(0, this->height() - 1, this->width(), this->height() - 1);
    p.drawLine(this->verticalPointerOffset, 0, this->verticalPointerOffset, this->height() / 8);
    p.drawLine(this->verticalPointerOffset, this->height() - (this->height() / 8), this->verticalPointerOffset, this->height());
}

void SpeedReaderLabel::processNextWordAvailable(QString w, int shift)
{
    this->clear();

    QFontMetrics fm(this->font());
    int indent = shift * fm.width("1");

    this->setIndent(indent);
    this->setText(w.replace(this->coloredSymbolPosition, 1, QString("<font color=\"%1\">").arg(this->symbolColor) + QString(w.at(this->coloredSymbolPosition)) + "</font>"));
}
